package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.audiorecordmp3demo.utils.RecorderAndPlayUtil;
import com.example.lamemp3.MP3Recorder;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.ToastUtils;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class MicAddActivity extends Activity {
    private RelativeLayout mic_circle;
    private ImageView audioMic;
    private ImageView add_mic_pause;
    private ImageView playDelete;
    private ImageView playSure;
    private TextView micTip;
    private TextView micAnimationtime;
    private Handler mHandler = new Handler();
    private Handler mdialogHandler = new Handler();
    private boolean isShosrt = false;
    private long startVoiceT, endVoiceT;
    public static String mMp3FileName;
    private boolean isStartRecord;
    private MediaPlayer mMediaPlayer = null;
    private ImageView lineplay;
    private Gson gson;
    private BaseApplication application;                // 应用主体
    private HttpConfig mHttpConfig;
    private static final String DIR = "yinian/LAME/mp3/";
    private Context mContext;
    private boolean mIsRecording = false;
    private boolean mIsSendVoice = false;
    private RecorderAndPlayUtil mRecorderUtil = null;
    private TimerTask mTimerTask = null;
    private Timer mTimer = null;
    boolean mainMic = false;
    private ProgressBar mProgressBar;
    private int mictime;
    private int backtime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.act_add_mic);
        mContext = MicAddActivity.this;
        gson = new Gson();
        application = (BaseApplication) getApplication();
        mHttpConfig = new HttpConfig(MicAddActivity.this);
        if (getIntent() != null) {
            mainMic = getIntent().getBooleanExtra("mainMic", false);
        }
        initView();
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    }
                    break;
            }
        }
    };


    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    public void ToSetDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否放弃编辑？");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("继续编辑");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("确定");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (add_mic_pause.getVisibility() == View.VISIBLE || lineplay.getVisibility() == View.VISIBLE) {
                    isShosrt = true;
                    mHandler.postDelayed(new Runnable() {
                        public void run() {
                            isShosrt = false;
                        }
                    }, 500);
                    isStartRecord = false;
                    initRecording();
                    MainActivity.micpath = "";
                    MainActivity.mp3IsExist = false;
                    mMp3FileName = "";
                    MainActivity.timer = 0;
                    finish();
                } else {
                    finish();
                }
                dlg.cancel();
            }
        });
    }

    Timer backTimer;
    Handler tthandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                micAnimationtime.setText(TimeUtils.secToTime(backtime--));
            } else if (msg.what == 2) {
                micAnimationtime.setText(TimeUtils.secToTime(mictime));
            }
        }
    };

    @Override
    public void onBackPressed() {
        if (mainMic) {
            ToSetDialog();
        } else {
            if (!MainActivity.mp3IsExist) {
                if (add_mic_pause.getVisibility() == View.VISIBLE) {
                    isShosrt = true;
                    mHandler.postDelayed(new Runnable() {
                        public void run() {
                            isShosrt = false;
                        }
                    }, 500);
                    isStartRecord = false;
                    initRecording();
                    MainActivity.micpath = "";
                    MainActivity.mp3IsExist = false;
                    mMp3FileName = "";
                    MainActivity.timer = 0;
                    sendBroadcast(new Intent(ACTIONs.actionMIcText));
                    finish();
                } else if (lineplay.getVisibility() == View.VISIBLE) {
                    doDeleteMic();
                    sendBroadcast(new Intent(ACTIONs.actionMIcText));
                    finish();
                } else {
                    sendBroadcast(new Intent(ACTIONs.actionMIcText));
                    finish();
                }
            } else {
                sendBroadcast(new Intent(ACTIONs.actionMIcText));
                finish();
            }
        }
    }

    private void initView() {
        mMediaPlayer = new MediaPlayer();
        mic_circle = (RelativeLayout) findViewById(R.id.mic_circle);
        audioMic = (ImageView) findViewById(R.id.add_mic);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        add_mic_pause = (ImageView) findViewById(R.id.add_mic_pause);
        lineplay = (ImageView) findViewById(R.id.add_mic_play);
        playDelete = (ImageView) findViewById(R.id.add_mic_del);
        playSure = (ImageView) findViewById(R.id.add_mic_ok);
        micTip = (TextView) findViewById(R.id.mcard_audio_mic_tip);
        micAnimationtime = (TextView) findViewById(R.id.mcard_audiomic_time);
        if (mainMic) {
            findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToSetDialog();
                }
            });
        } else {
            findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!MainActivity.mp3IsExist) {
                        if (add_mic_pause.getVisibility() == View.VISIBLE) {
                            isShosrt = true;
                            mHandler.postDelayed(new Runnable() {
                                public void run() {
                                    isShosrt = false;
                                }
                            }, 500);
                            isStartRecord = false;
                            initRecording();
                            MainActivity.micpath = "";
                            MainActivity.mp3IsExist = false;
                            mMp3FileName = "";
                            MainActivity.timer = 0;
                            sendBroadcast(new Intent(ACTIONs.actionMIcText));
                            finish();
                        } else if (lineplay.getVisibility() == View.VISIBLE) {
                            doDeleteMic();
                            finish();
                        } else {
                            finish();
                        }
                    } else {
                        finish();
                    }

                }
            });
        }
        mRecorderUtil = new RecorderAndPlayUtil(DIR);
        mRecorderUtil.getRecorder().setHandle(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MP3Recorder.MSG_REC_STARTED:
                        // 开始录音
                        break;
                    case MP3Recorder.MSG_REC_STOPPED:
                        if (mIsSendVoice) {// 是否发送录音
                            mIsSendVoice = false;
                            // Toast.makeText(mContext, "停止录音", Toast.LENGTH_SHORT).show();
//                            mMp3FileName = mRecorderUtil.getRecorderPath();
                        }
                        break;
                    case MP3Recorder.MSG_ERROR_GET_MIN_BUFFERSIZE:
                        initRecording();
                        Toast.makeText(mContext, "采样率手机不支持", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_CREATE_FILE:
                        initRecording();
                        Toast.makeText(mContext, "创建音频文件出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_REC_START:
                        initRecording();
                        Toast.makeText(mContext, "初始化录音器出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_AUDIO_RECORD:
                        initDialog();
                        initRecording();
                        Toast.makeText(mContext, "录音的时候出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_AUDIO_ENCODE:
                        initRecording();
                        Toast.makeText(mContext, "编码出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_WRITE_FILE:
                        initRecording();
                        Toast.makeText(mContext, "文件写入出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_CLOSE_FILE:
                        initRecording();
                        Toast.makeText(mContext, "文件流关闭出错", Toast.LENGTH_SHORT).show();
                        break;
                    case MP3Recorder.MSG_ERROR_AUDIO_LENGHT_NULL:
                        initDialog();
                        initRecording();
                        doDeleteMic();
                        break;
                }
            }
        });
        mic_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (audioMic.getVisibility() == View.VISIBLE) {
                    audioMic.setVisibility(View.GONE);
                    micTip.setVisibility(View.GONE);
                    micAnimationtime.setText("00:00:00");
                    micAnimationtime.setVisibility(View.VISIBLE);
                    add_mic_pause.setVisibility(View.VISIBLE);
                    startVoiceT = System.currentTimeMillis();
                    isStartRecord = true;
                    down();
                } else if (add_mic_pause.getVisibility() == View.VISIBLE) {
                    if (isStartRecord) {
                        endVoiceT = System.currentTimeMillis();
                        MainActivity.timer = (int) ((endVoiceT - startVoiceT) / 1000);
                        if (MainActivity.timer < 2) {
                            // 停止录音
                            isShosrt = true;
                            mHandler.postDelayed(new Runnable() {
                                public void run() {
                                    isShosrt = false;
                                }
                            }, 500);
                            isStartRecord = false;
                            initRecording();
                            micAnimationtime.setText("00:00:00");
                            micAnimationtime.setVisibility(View.GONE);
                            micTip.setVisibility(View.VISIBLE);
                            add_mic_pause.setVisibility(View.GONE);
                            audioMic.setVisibility(View.VISIBLE);
                            Toast.makeText(mContext, "至少录制2s！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (mIsRecording) {
                            initRecording();
                            mMp3FileName = mRecorderUtil.getRecorderPath();
                            MainActivity.micpath = mMp3FileName;
                            Message message = new Message();
                            message.obj = true;
                            flameHandler.sendMessage(message);
                        }
                        uploadMICfile();
                    }
                } else if (lineplay.getVisibility() == View.VISIBLE) {
                    if (StringUtils.isEmpty(MainActivity.micpath)) {
                        if (isStartRecord) {
                            isStartRecord = false;
                        }
                        File file = new File(mMp3FileName);
                        if (!file.exists()) {
                            Toast.makeText(MicAddActivity.this, "没有音乐文件！", Toast.LENGTH_SHORT).show();
                            lineplay.setVisibility(View.GONE);
                            audioMic.setVisibility(View.VISIBLE);
                            micAnimationtime.setVisibility(View.GONE);
                            micTip.setVisibility(View.VISIBLE);
                            playDelete.setVisibility(View.GONE);
                            playSure.setVisibility(View.GONE);
                            return;
                        }
                    }
                    if (mMediaPlayer.isPlaying()) {
                        lineplay.setImageResource(R.drawable.add_mic_play);
                        mMediaPlayer.stop();
                        try {
                            mMediaPlayer.prepare();//stop后下次重新播放要首先进入prepared状态
                            mMediaPlayer.seekTo(0);//须将播放时间设置到0；这样才能在下次播放是重新开始，否则会继续上次播放
                            if (backTimer != null)
                                backTimer.cancel();
                            tthandler.sendEmptyMessage(2);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        lineplay.setImageResource(R.drawable.add_mic_pause);
                        mMediaPlayer.start();
                        backtime = mictime;
                        backTimer = new Timer();
                        TimerTask mTimerTask = new TimerTask() {
                            @Override
                            public void run() {
                                tthandler.sendEmptyMessage(1);
                            }
                        };
                        backTimer.schedule(mTimerTask, 0, 1000);
                    }
                }
            }
        });
//        audioMic.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        add_mic_pause.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        try {
//            audioMic.setOnTouchListener(new MyClickListener());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        lineplay.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mictime = mp.getDuration() / 1000;
                if (backTimer != null) {
                    backTimer.cancel();
                }
                tthandler.sendEmptyMessage(2);
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                lineplay.setImageResource(R.drawable.add_mic_play);
                if (MainActivity.mp3IsExist && !StringUtils.isEmpty(MainActivity.micpath)) {
                    try {
                        mp.stop();
                        mp.reset();
                        mp.setDataSource(MainActivity.micpath);
                        mp.prepare();
                        if (backTimer != null)
                            backTimer.cancel();
                        tthandler.sendEmptyMessage(2);
                    } catch (IOException e) {
                        e.printStackTrace();
                        lineplay.setVisibility(View.GONE);
                        audioMic.setVisibility(View.VISIBLE);
                        micAnimationtime.setVisibility(View.GONE);
                        micTip.setVisibility(View.VISIBLE);
                        playDelete.setVisibility(View.GONE);
                        playSure.setVisibility(View.GONE);
                        return;
                    }
                    return;
                }
                if (StringUtils.isEmpty(mMp3FileName))
                    return;
                File file = new File(mMp3FileName);
                try {
                    if (file.exists() && file.length() > 1) {
                        mp.stop();
                        mp.reset();
                        mp.setDataSource(mMp3FileName);
                        mp.prepare();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        playDelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mMp3FileName))
                    return;
                DelMicDialog();
            }
        });
        playSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mMp3FileName)) {
                    ToastUtils.showToast(MicAddActivity.this, "录音后确认!", 300);
                    return;
                }
                if (!mainMic) {
                    Intent mIntent = new Intent(ACTIONs.actionMIcText);
                    sendBroadcast(mIntent);
                    finish();
                    return;
                }
                if (mMediaPlayer.isPlaying()) {
                    lineplay.setImageResource(R.drawable.add_mic_play);
                    mMediaPlayer.stop();
                    try {
                        mMediaPlayer.prepare();//stop后下次重新播放要首先进入prepared状态
                        mMediaPlayer.seekTo(0);//须将播放时间设置到0；这样才能在下次播放是重新开始，否则会继续上次播放
                        if (backTimer != null)
                            backTimer.cancel();
                        tthandler.sendEmptyMessage(2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                startActivity(new Intent(MicAddActivity.this, MicEditActivity.class));
                Intent mIntent = new Intent(ACTIONs.actionMIcText);
                sendBroadcast(mIntent);
            }
        });
        if (MainActivity.mp3IsExist && !StringUtils.isEmpty(MainActivity.micpath)) {
            lineplay.setVisibility(View.VISIBLE);
            audioMic.setVisibility(View.GONE);
            micTip.setVisibility(View.GONE);
            micAnimationtime.setVisibility(View.VISIBLE);
            micAnimationtime.setText(TimeUtils.secToTime(MainActivity.timer));
            playDelete.setVisibility(View.VISIBLE);
//            playSure.setVisibility(View.GONE);
            try {
                mMediaPlayer.setDataSource(MainActivity.micpath);
                mMediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
                lineplay.setVisibility(View.GONE);
                audioMic.setVisibility(View.VISIBLE);
//                micTip.setText("点击录制");
                micAnimationtime.setVisibility(View.GONE);
                micTip.setVisibility(View.VISIBLE);
                return;
            }
        } else {
            lineplay.setVisibility(View.GONE);
            audioMic.setVisibility(View.VISIBLE);
            micAnimationtime.setVisibility(View.GONE);
            micTip.setVisibility(View.VISIBLE);
        }

    }

    public void DelMicDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否删除已录入的声音");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("删除");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doDeleteMic();
                dlg.cancel();
            }
        });
    }

    private void doDeleteMic() {
        lineplay.setVisibility(View.GONE);
        audioMic.setVisibility(View.VISIBLE);
//        micAnimationtime.setText("00:00:00");
//        micTip.setText("点击录制");
        micAnimationtime.setVisibility(View.GONE);
        micTip.setVisibility(View.VISIBLE);
        playDelete.setVisibility(View.GONE);
        playSure.setVisibility(View.GONE);
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
        }
        MainActivity.micpath = "";
        MainActivity.timer = 0;
        MainActivity.mp3IsExist = false;
        MainActivity.micUrl = "";
        mMp3FileName = "";
    }

    private void initDialog() {
        final Dialog canceldialog = new Dialog(this, R.style.dialog_remain_gift);
        final View cancelView = LayoutInflater.from(application).inflate(R.layout.yn_mic_lenght_null, null);
        cancelView.findViewById(R.id.micnull_tip_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                canceldialog.dismiss();
            }
        });
        canceldialog.setContentView(cancelView);
        canceldialog.show();
    }

    private void down() {
        if (mTimer != null) mTimer.cancel();
        if (mTimerTask != null) mTimerTask.cancel();
        mIsRecording = true;
        mTimerTask = new TimerTask() {
            int i = 1000;
            int j = 0;

            @Override
            public void run() {
                i--;
                j += 1;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        micAnimationtime.setText(TimeUtils.secToTime(j));
                    }
                });
                if (i == 0) {
                    mIsSendVoice = true;
                    mdialogHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            // 录音结束
                            mTimer.cancel();
                            mTimerTask.cancel();
                            mIsRecording = false;
                            mRecorderUtil.stopRecording();
                        }
                    });
                }
                if (i < 0) {
                    mTimer.cancel();
                    mTimerTask.cancel();
                }
            }
        };
        mRecorderUtil.startRecording();
        mTimer = new Timer(true);
        mTimer.schedule(mTimerTask, 1000, 1000);
    }

    private void initRecording() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
        mRecorderUtil.stopRecording();
        mIsRecording = false;
        mRecorderUtil.getRecorderPath();
    }

    public void uploadMICfile() {
        final String micname = mMp3FileName;
        if (!StringUtils.isEmpty(micname)) {
            File file = new File(micname);
            if (!file.exists()) {
                Toast.makeText(MicAddActivity.this, "无效音频文件，请重录！", Toast.LENGTH_SHORT)
                        .show();
                lineplay.setVisibility(View.GONE);
                audioMic.setVisibility(View.VISIBLE);
                micAnimationtime.setVisibility(View.GONE);
                micTip.setVisibility(View.VISIBLE);
                return;
            }
            if (file.length() < 1) {
                Toast.makeText(MicAddActivity.this, "录音过短！", Toast.LENGTH_SHORT).show();
                return;
            }
            getToken();
        } else {
            Toast.makeText(MicAddActivity.this, "无效音频文件，请重录！", Toast.LENGTH_SHORT)
                    .show();
            lineplay.setVisibility(View.GONE);
            audioMic.setVisibility(View.VISIBLE);
            micAnimationtime.setVisibility(View.GONE);
            micTip.setVisibility(View.VISIBLE);
            return;
        }
    }

    private void getToken() {
        mProgressBar.setVisibility(View.VISIBLE);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetPrivateSpaceUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getMicAddress();
                        } else {
                            Toast.makeText(MicAddActivity.this, resToken.getMsg(), Toast.LENGTH_SHORT)
                                    .show();
                            mProgressBar.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(MicAddActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT)
                                .show();
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
        LiteHttp.newApacheHttpClient(mHttpConfig).executeAsync(req);
    }


    private void getMicAddress() {
        String prefix = mMp3FileName.substring(mMp3FileName.lastIndexOf(".") + 1);
        final String imgName = UUID.randomUUID().toString() + "." + prefix;
        application.getUploadManager().put(mMp3FileName, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        MainActivity.micUrl = key;
                        mProgressBar.setVisibility(View.GONE);
                        MainActivity.mp3IsExist = true;
                        add_mic_pause.setVisibility(View.GONE);
                        lineplay.setVisibility(View.VISIBLE);
                        playDelete.setVisibility(View.VISIBLE);
                        playSure.setVisibility(View.VISIBLE);
                    }

                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                            }
                        }, null));
    }

    Handler flameHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj != null) {
                boolean fbb = (Boolean) msg.obj;
                if (fbb) {
                    audioMic.setVisibility(View.GONE);
                    lineplay.setVisibility(View.VISIBLE);
                    try {
                        mMediaPlayer.reset();
                        mMediaPlayer.setDataSource(mMp3FileName);
                        mMediaPlayer.prepare();
                    } catch (IOException e) {
                        Log.e("xjs", "播放失败");
                    }
//                    playTime.setText(String.valueOf(timer) + "”");
                }
            }
        }
    };

//    class MyClickListener implements View.OnTouchListener {
//        public boolean onTouch(View v, MotionEvent event) {
//            switch (event.getAction()) {
//                case MotionEvent.ACTION_UP:
//                    // 正常放开，接下来一般做以下事情：发送录音文件到服务器
//
//                    break;
//                case MotionEvent.ACTION_CANCEL:
//                    // 异常放开，接下来一般做以下事情：删除录音文件
//                    // 停止录音
//                    micAnimationtime.setText(TimeUtils.secToTime(0));
//                    isStartRecord = false;
////                    File file = new File(mRecordFileName);
////                    if (file.exists()) {
////                        file.delete();
////                    }
//                    break;
//            }
//            return false;
//        }
//    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null)
            mMediaPlayer.stop();
        if (mainMic) {
            SelectedImg.mSelectedImage.clear();
            AiteSelectActivity.phoneNames.clear();
            MicAddActivity.mMp3FileName = "";
            MainActivity.mp3IsExist = false;
            MainActivity.micUrl = "";
            MainActivity.micpath = "";
            MainActivity.locationTx = "";
        }
        this.unregisterReceiver(mBroadcastReceiver);
    }
}
